<template>
  <div class="dashboard">
    <!-- 顶部导航栏 -->
    <el-header class="dashboard-header">
      <div class="header-left">
        <img src="/logo.png" alt="Matrix Framework" class="logo" />
        <h1>Matrix Framework</h1>
      </div>

      <div class="header-center">
        <el-menu
          :default-active="activeMenu"
          mode="horizontal"
          @select="handleMenuSelect"
        >
          <el-menu-item index="overview">
            <el-icon><Monitor /></el-icon>
            概览
          </el-menu-item>
          <el-menu-item index="users" v-if="canManageUsers">
            <el-icon><User /></el-icon>
            用户管理
          </el-menu-item>
          <el-menu-item index="tenants" v-if="canManageTenants">
            <el-icon><OfficeBuilding /></el-icon>
            租户管理
          </el-menu-item>
          <el-menu-item index="settings">
            <el-icon><Setting /></el-icon>
            系统设置
          </el-menu-item>
        </el-menu>
      </div>

      <div class="header-right">
        <!-- 租户切换 -->
        <el-dropdown v-if="userTenants.length > 1">
          <el-button text>
            <el-icon><OfficeBuilding /></el-icon>
            {{ currentTenant?.displayName }}
            <el-icon><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                v-for="tenant in userTenants"
                :key="tenant.id"
                @click="switchTenant(tenant)"
              >
                <el-icon><OfficeBuilding /></el-icon>
                {{ tenant.displayName }}
                <el-tag v-if="tenant.id === currentTenant?.id" size="small">
                  当前
                </el-tag>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>

        <!-- 用户菜单 -->
        <el-dropdown @command="handleUserCommand">
          <el-button text>
            <el-avatar :size="32" :src="userAvatar">
              {{ authService.user?.name?.charAt(0) || 'U' }}
            </el-avatar>
            <span class="username">{{ authService.user?.displayName || '用户' }}</span>
            <el-icon><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">
                <el-icon><User /></el-icon>
                个人资料
              </el-dropdown-item>
              <el-dropdown-item command="settings">
                <el-icon><Setting /></el-icon>
                账户设置
              </el-dropdown-item>
              <el-dropdown-item divided command="logout">
                <el-icon><SwitchButton /></el-icon>
                退出登录
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-header>

    <!-- 主要内容区域 -->
    <el-main class="dashboard-main">
      <!-- 概览页面 -->
      <div v-if="activeMenu === 'overview'" class="overview">
        <h2>欢迎回来，{{ authService.user?.displayName || '用户' }}！</h2>

        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-icon users">
                  <el-icon><User /></el-icon>
                </div>
                <div class="stat-info">
                  <h3>{{ stats.userCount }}</h3>
                  <p>总用户数</p>
                </div>
              </div>
            </el-card>
          </el-col>

          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-icon tenants">
                  <el-icon><OfficeBuilding /></el-icon>
                </div>
                <div class="stat-info">
                  <h3>{{ stats.tenantCount }}</h3>
                  <p>租户数量</p>
                </div>
              </div>
            </el-card>
          </el-col>

          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-icon logins">
                  <el-icon><Connection /></el-icon>
                </div>
                <div class="stat-info">
                  <h3>{{ stats.todayLogins }}</h3>
                  <p>今日登录</p>
                </div>
              </div>
            </el-card>
          </el-col>

          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-icon storage">
                  <el-icon><FolderOpened /></el-icon>
                </div>
                <div class="stat-info">
                  <h3>{{ stats.storageUsed }}</h3>
                  <p>存储使用</p>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 最近活动 -->
        <el-card class="activity-card" style="margin-top: 20px;">
          <template #header>
            <div class="card-header">
              <h3>最近活动</h3>
              <el-button text @click="refreshActivities">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </template>

          <el-timeline>
            <el-timeline-item
              v-for="activity in recentActivities"
              :key="activity.id"
              :timestamp="activity.timestamp"
              :type="activity.type"
            >
              {{ activity.description }}
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </div>

      <!-- 用户管理页面 -->
      <div v-else-if="activeMenu === 'users'" class="users-management">
        <div class="page-header">
          <h2>用户管理</h2>
          <el-button type="primary" @click="showCreateUserDialog">
            <el-icon><Plus /></el-icon>
            新增用户
          </el-button>
        </div>

        <el-table :data="users" style="width: 100%">
          <el-table-column prop="username" label="用户名" />
          <el-table-column prop="email" label="邮箱" />
          <el-table-column prop="displayName" label="显示名称" />
          <el-table-column prop="status" label="状态">
            <template #default="{ row }">
              <el-tag :type="row.isActive ? 'success' : 'danger'">
                {{ row.isActive ? '活跃' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="lastLogin" label="最后登录" />
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button size="small" @click="editUser(row)">编辑</el-button>
              <el-button size="small" type="danger" @click="deleteUser(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 租户管理页面 -->
      <div v-else-if="activeMenu === 'tenants'" class="tenants-management">
        <div class="page-header">
          <h2>租户管理</h2>
          <el-button type="primary" @click="showCreateTenantDialog">
            <el-icon><Plus /></el-icon>
            新增租户
          </el-button>
        </div>

        <el-table :data="tenants" style="width: 100%">
          <el-table-column prop="name" label="租户名称" />
          <el-table-column prop="displayName" label="显示名称" />
          <el-table-column prop="keycloakRealm" label="Keycloak Realm" />
          <el-table-column prop="userCount" label="用户数量" />
          <el-table-column prop="status" label="状态">
            <template #default="{ row }">
              <el-tag :type="row.isActive ? 'success' : 'danger'">
                {{ row.isActive ? '活跃' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button size="small" @click="editTenant(row)">编辑</el-button>
              <el-button size="small" type="primary" @click="configTenant(row)">配置</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-main>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Monitor, User, OfficeBuilding, Setting, ArrowDown,
  SwitchButton, Connection, FolderOpened, Refresh, Plus
} from '@element-plus/icons-vue'
import authService from '@/services/AuthService'

interface User {
  id: string
  username: string
  email: string
  displayName: string
  isActive: boolean
  lastLogin: string
}

interface Tenant {
  id: string
  name: string
  displayName: string
  keycloakRealm: string
  userCount: number
  isActive: boolean
}

interface Activity {
  id: string
  description: string
  timestamp: string
  type: 'primary' | 'success' | 'warning' | 'danger'
}

const router = useRouter()

// 响应式数据
const activeMenu = ref('overview')
const stats = ref({
  userCount: 1250,
  tenantCount: 15,
  todayLogins: 342,
  storageUsed: '2.3TB'
})

const users = ref<User[]>([
  {
    id: '1',
    username: 'admin',
    email: 'admin@matrixframework.com',
    displayName: '系统管理员',
    isActive: true,
    lastLogin: '2024-10-26 18:30'
  }
])

const tenants = ref<Tenant[]>([
  {
    id: 'default-tenant',
    name: 'default-tenant',
    displayName: 'Matrix Framework',
    keycloakRealm: 'MatrixFramework',
    userCount: 1250,
    isActive: true
  }
])

const recentActivities = ref<Activity[]>([
  {
    id: '1',
    description: '用户 admin 登录系统',
    timestamp: '2024-10-26 18:30',
    type: 'success'
  },
  {
    id: '2',
    description: '租户 "示例租户" 创建成功',
    timestamp: '2024-10-26 17:45',
    type: 'primary'
  }
])

const currentTenant = computed(() => {
  return tenants.value.find(t => t.id === authService.tenantInfo?.id)
})

const userTenants = computed(() => {
  // 根据用户权限返回可访问的租户
  return tenants.value.filter(t => t.isActive)
})

const userAvatar = computed(() => {
  return authService.user?.avatar || ''
})

const canManageUsers = computed(() => {
  return authService.hasPermission('user.manage')
})

const canManageTenants = computed(() => {
  return authService.hasPermission('tenant.manage')
})

// 生命周期
onMounted(async () => {
  await loadDashboardData()
})

// 方法
const loadDashboardData = async () => {
  try {
    // 这里应该调用实际的API获取数据
    console.log('加载仪表板数据...')
  } catch (error) {
    console.error('加载数据失败:', error)
  }
}

const handleMenuSelect = (index: string) => {
  activeMenu.value = index
}

const handleUserCommand = async (command: string) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'settings':
      ElMessage.info('账户设置功能开发中...')
      break
    case 'logout':
      await handleLogout()
      break
  }
}

const handleLogout = async () => {
  try {
    const result = await authService.logout()
    if (result.success) {
      ElMessage.success('已安全退出')
      router.push('/login')
    } else {
      ElMessage.error('退出失败: ' + result.error)
    }
  } catch (error) {
    console.error('退出异常:', error)
    ElMessage.error('退出异常')
  }
}

const switchTenant = async (tenant: Tenant) => {
  try {
    ElMessage.info(`切换到租户: ${tenant.displayName}`)
    // 这里应该实现实际的租户切换逻辑
  } catch (error) {
    ElMessage.error('租户切换失败')
  }
}

const refreshActivities = () => {
  ElMessage.success('活动列表已刷新')
  // 重新加载活动数据
}

const showCreateUserDialog = () => {
  ElMessage.info('新增用户功能开发中...')
}

const showCreateTenantDialog = () => {
  ElMessage.info('新增租户功能开发中...')
}

const editUser = (user: User) => {
  ElMessage.info(`编辑用户: ${user.username}`)
}

const deleteUser = async (user: User) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${user.username}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    ElMessage.success('用户删除成功')
    // 实际删除逻辑
  } catch {
    // 用户取消删除
  }
}

const editTenant = (tenant: Tenant) => {
  ElMessage.info(`编辑租户: ${tenant.displayName}`)
}

const configTenant = (tenant: Tenant) => {
  ElMessage.info(`配置租户: ${tenant.displayName}`)
}
</script>

<style scoped>
.dashboard {
  min-height: 100vh;
  background: #f5f7fa;
}

.dashboard-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: white;
  border-bottom: 1px solid #e9ecef;
  padding: 0 2rem;
  height: 60px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.logo {
  width: 32px;
  height: 32px;
  border-radius: 6px;
}

.header-left h1 {
  font-size: 1.25rem;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.header-center {
  flex: 1;
  display: flex;
  justify-content: center;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.username {
  margin-left: 0.5rem;
  font-weight: 500;
}

.dashboard-main {
  padding: 2rem;
}

.overview h2 {
  margin-bottom: 2rem;
  color: #333;
}

.stat-card {
  transition: transform 0.2s;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.5rem;
  color: white;
}

.stat-icon.users {
  background: linear-gradient(135deg, #667eea, #764ba2);
}

.stat-icon.tenants {
  background: linear-gradient(135deg, #f093fb, #f5576c);
}

.stat-icon.logins {
  background: linear-gradient(135deg, #4facfe, #00f2fe);
}

.stat-icon.storage {
  background: linear-gradient(135deg, #43e97b, #38f9d7);
}

.stat-info h3 {
  font-size: 1.5rem;
  font-weight: 700;
  margin: 0;
  color: #333;
}

.stat-info p {
  font-size: 0.9rem;
  color: #666;
  margin: 0.25rem 0 0 0;
}

.activity-card .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.activity-card h3 {
  margin: 0;
  color: #333;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .dashboard-header {
    padding: 0 1rem;
  }

  .header-center {
    display: none;
  }

  .dashboard-main {
    padding: 1rem;
  }
}
</style>